﻿using NLog;
using StructuredProgrammingAssignment.App_Start;
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web;

namespace StructuredProgrammingAssignment.Models
{
	public class SPLog
	{
		private static Logger _logger = LogManager.GetCurrentClassLogger();

		public static void Info(string name, string message, string controller,	string action, string path) {
			SPLog.Log(LogLevel.Info, name, message, controller, action, path);
		}

		public static void Warn(string name, string message, string controller, string action, string path) {
			SPLog.Log(LogLevel.Warn, name, message, controller, action, path);
		}

		public static void Debug(string name, string message, string controller, string action, string path) {
			SPLog.Log(LogLevel.Debug, name, message, controller, action, path);
		}

		public static void Error(string name, string message, string controller, string action, string path) {
			SPLog.Log(LogLevel.Error, name, message, controller, action, path);
		}

		public static void Fatal(string name, string message, string controller, string action, string path) {
			SPLog.Log(LogLevel.Fatal, name, message, controller, action, path);
		}

		public static void Trace(string name, string message, string controller, string action, string path) {
			SPLog.Log(LogLevel.Trace, name, message, controller, action, path);
		}

		public static void Log(LogLevel level, string name,	string message, string controller, string action, string path
		) {
			LogEventInfo info = new LogEventInfo(level, name, message);

			string urlpath = path.Substring(0, path.IndexOf('?'));
			string urlquery = path.Substring(path.IndexOf('?'));

			string parsedquery = urlquery;
			NameValueCollection filter = new NameValueCollection(HttpUtility.ParseQueryString(urlquery.ToLower()));
			foreach (string paramFilter in SPConfig.Settings.SensitiveLogParams.ValueList()) {
				if (filter.AllKeys.Contains(paramFilter)) {
					filter.Set(paramFilter, "***");
				}
			}
			parsedquery = "?" + String.Join("&", filter.AllKeys.Select(key => key + "=" + filter[key]).ToArray());

			info.Properties.Add("controller", controller);
			info.Properties.Add("action", action);
			info.Properties.Add("path", urlpath + parsedquery);
			info.Properties.Add("hostaddress", HttpContext.Current.Request.UserHostAddress);

			_logger.Log(info);
		}
	}
}